package com.learn.project2.config.shiro.realm;

import com.learn.project2.bean.*;
import com.learn.project2.config.customException.RealmFailException;
import com.learn.project2.mapper.MarketPermissionMapper;
import com.learn.project2.mapper.MarketUserMapper;
import com.learn.project2.model.bo.wx.auth.AuthLoginBO2;
import com.learn.project2.utils.SecretUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * \* Author: Valley
 * \* Date: 2022/1/10
 * \* Time: 21:47
 * \* Description:
 */
@Component
public class WxRealm extends AuthorizingRealm {

    @Autowired
    MarketPermissionMapper permissionMapper;
    @Autowired
    MarketUserMapper userMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal = (String) authenticationToken.getPrincipal();
        MarketUserExample userExample = new MarketUserExample();
        userExample.createCriteria()
                .andUsernameEqualTo(principal).andDeletedEqualTo(false);
        List<MarketUser> marketUsers = userMapper.selectByExample(userExample);
        if (marketUsers.size() <= 0){
            try {
                throw new RealmFailException();
            } catch (RealmFailException e) {
                e.printStackTrace();
            }
        }
        return new SimpleAuthenticationInfo(marketUsers.get(0),  marketUsers.get(0).getUsername(), getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        MarketAdmin admin  = (MarketAdmin) principalCollection.getPrimaryPrincipal();
        List<Integer> list = new ArrayList<>();
        Collections.addAll(list,admin.getRoleIds());

        MarketPermissionExample example = new MarketPermissionExample();
        example.createCriteria().andRoleIdIn(list);

        List<MarketPermission> marketPermissions = permissionMapper.selectByExample(example);

        List<String> permissions = new ArrayList<>();
        for (MarketPermission marketPermission : marketPermissions) {
            permissions.add(marketPermission.getPermission());
        }

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permissions);


        return authorizationInfo;
    }
}
